<template>
  <ul>
    <li><input type="text" placeholder="Filter" ref="filter" v-model="filter" /></li>
    <li><div class="separator"></div></li>
    <template v-for="(category, index) in categories">
      <li :key="category.title" v-if="filterCategory(index)" @click="() => handleClickCategory(index)">
        <div class="menu-item">
          <div
            class="codicon"
            :class="{ 'codicon-chevron-down': expands[index], 'codicon-chevron-right': !expands[index] }"
          />
          <span>{{ category.title }}</span>
        </div>
      </li>
      <template v-if="expands[index]">
        <template v-for="node in category.nodes">
          <li v-if="filterNode(node)" :key="node.title" @click="() => handleClickNode(category, node)">
            <div class="menu-item" v-if="filterNode(node)">
              {{ node.title }}
            </div>
          </li>
        </template>
      </template>
    </template>
  </ul>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  data() {
    return {
      filter: '',
      expands: [],
    };
  },

  mounted() {
    this.expands = this.categories.map(() => false);
    this.$refs.filter.focus();
  },

  methods: {
    ...mapMutations(['addNode', 'addLinks']),

    handleClickCategory(index) {
      this.$set(this.expands, index, !this.expands[index]);
    },

    handleClickNode(category, node) {
      this.addNode({ category, node });
    },

    filterCategory(index) {
      const category = this.categories[index];
      if (this.filter.length === 0) {
        return true;
      } else {
        const result = category.nodes.findIndex((x) => x.title.includes(this.filter)) >= 0;
        this.expands[index] = result;
        return result;
      }
    },

    filterNode(node) {
      return node.title.includes(this.filter);
    },
  },

  computed: {
    ...mapState(['categories', 'linkingPins', 'maxId']),
  },
};
</script>
